package com.bw.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.bw.service.goods.SkuSearchService;
import com.bw.util.WebUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Controller
public class SearchController {

    @Reference
    private SkuSearchService skuSearchService;

    @GetMapping("/search")
    public String search(Model model, @RequestParam Map<String,String> searchMap) throws Exception {
        //字符集处理
        searchMap = WebUtil.convertCharsetToUTF8(searchMap);

        //排序参数容错处理
        // 页面传递给后端 两个参数  sort:排序字段  sortOrder  排序规则（升序/降序）
        if(searchMap.get("sort")==null){//排序字段
            searchMap.put("sort","");
        }
        if(searchMap.get("sortOrder")==null){//排序规则
            searchMap.put("sortOrder","DESC");
        }

        //接受页码处理,如果不传递页码默认为第1页
        if(searchMap.get("pageNo")==null){
            searchMap.put("pageNo","1");
        }

        //url处理
        StringBuffer url = new StringBuffer("/search.do?");
        for (String key : searchMap.keySet()) {
            url.append("&"+key+"="+searchMap.get(key));
        }
        model.addAttribute("url",url);


        //远程调用接口
        Map result = skuSearchService.search(searchMap);
        model.addAttribute("result",result);

        int pageNo =Integer.parseInt(searchMap.get("pageNo")) ;//当前页

        Long totalPages= (Long) result.get("totalPages");//得到总页数
        int startPage=1;//开始页码
        int endPage =totalPages.intValue();//截至代码
        if(totalPages>5){
            startPage=pageNo-2;
            if(startPage<1){
                startPage=1;
            }
            endPage=startPage+4;
        }
        model.addAttribute("startPage",startPage);//开始页码
        model.addAttribute("endPage",endPage);//结束页码

        model.addAttribute("pageNo",pageNo);//当前页码

        model.addAttribute("searchMap",searchMap);
        return "search";
    }
}
